<script lang="ts">
	import { user, type User } from '$lib/AniList/user';
	import HeadTitle from '$lib/Home/HeadTitle.svelte';
	import { estimatedDayReading } from '$lib/Media/Manga/time';
	import Skeleton from '$lib/Skeleton.svelte';
	import root from '$lib/Utility/root.js';
	import { onMount } from 'svelte';

	export let data;

	let userData: User | undefined = undefined;

	onMount(() => {
		user(data.username).then((profile) => {
			userData = profile;
		});
	});

	// 8.5827814569536423841e0
</script>

<HeadTitle route={`${data.username}'s Profile`} path={`/user/${data.username}`} />

<div class={userData ? 'card card-small' : 'card'} id="user-panel">
	{#if userData === null}
		Could not load user profile for <a
			href={`https://anilist.co/user/${data.username}`}
			target="_blank">@{data.username}</a
		>.

		<p />

		Does this user exist?
	{:else if userData === undefined}
		<p>Loading user ... 50%</p>

		<Skeleton card={false} count={1} />
	{:else}
		<div
			class="card"
			id="user-grid"
			style={`background-image: ${userData ? `url(${userData.bannerImage})` : 'none'}; padding: 0;`}
		>
			{#if userData}
				<img src={userData.bannerImage} alt="" id="cover-image" />
			{/if}

			<div class="card" id="user-grid-content">
				<div id="user-grid-avatar">
					<a
						href={`https://anilist.co/user/${userData.name}`}
						target="_blank"
						title={String(userData.id)}
					>
						<img src={userData.avatar.large} alt="" width="100vw" id="avatar" />
					</a>
				</div>

				<div id="user-grid-content-text">
					<p>
						<a
							href={`https://anilist.co/user/${userData.name}`}
							target="_blank"
							title={String(userData.id)}>@{userData.name}</a
						>
						<span class="click-item">•</span>
						<a href={root(`/user/${userData.name}/badges`)}>Badge Wall</a>
					</p>

					{data.username} has watched {(userData.statistics.anime.minutesWatched / 60 / 24).toFixed(
						1
					)} days of anime and read
					{estimatedDayReading(userData.statistics.manga.chaptersRead).toFixed(1)} days of manga.

					<p />

					{data.username} has collected {#await fetch(root(`/api/badges?id=${userData.id}`))}
						...
					{:then badges}
						{#await badges.json()}
							...
						{:then badges}
							{badges.length}
						{:catch}
							?
						{/await}
					{:catch}
						?
					{/await}
					badges using Badge Wall.
				</div>
			</div>
		</div>
	{/if}
</div>

<style>
	#user-grid-content {
		display: flex;
		flex-wrap: wrap;
		column-gap: 1.5em;
		background-color: rgba(0, 0, 0, 0.468);
		color: #d8d8d8;
		border-top-left-radius: 0;
		border-top-right-radius: 0;
	}

	#user-grid-avatar {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	#avatar {
		border-radius: 8px;
	}

	.click-item {
		margin: 0 0.625rem;
	}

	#user-grid {
		background-size: cover;
		background-position: center;
		background-repeat: no-repeat;
	}

	#cover-image {
		visibility: hidden;
		height: 4.5em;
	}
</style>
